<template>
    <basic-container>
        <div style="display: flex; align-items: center;" v-if="routerQuery.selectTab">
            <ArrowLeftBold @click="initGoBackCase(false)" width="24" height="24"
                style="padding-top: 4px; cursor: pointer"  title="返回" />
                <p  style="margin-left: 10px; font-size: 18px">选择病例</p>
        </div>

        <avue-crud :option="options" v-model:search="search" v-model:page="page" v-model="form" :table-loading="loading"
            :data="data" :permission="permissionList" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
            @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad">
            <template #menu-left>
                <el-button type="danger" icon="el-icon-delete" plain
                    v-if="permission.trial_delete && !routerQuery.selectTab" @click="handleDelete">删 除
                </el-button>
                <!-- <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button> -->
            </template>
            <template #menu="{ row, index }">
                <el-button text plain @click="handleMenu(0, row, index)" style="color: #00c0ef"
                    v-if="!routerQuery.selectTab">查 看
                </el-button>
                <el-button text plain @click="handleMenu(1, row, index)" style="color: #3c8dbc"
                    v-if="!routerQuery.selectTab">编 辑
                </el-button>
                <el-button text plain @click="handleMenu(2, row, index)" style="color: #00a65a"
                    v-if="!routerQuery.selectTab">添加病例
                </el-button>
                <el-button text plain @click="handleMenu(3, row, index)" style="color: red"
                    v-if="!routerQuery.selectTab">删 除
                </el-button>
                <el-button text plain @click="handleMenu(5, row, index)" style="color: #0077bd"
                    v-if="routerQuery.selectTab">选 择
                </el-button>
            </template>
            <template #name="{ row }">
                <span style="color: #72afd2; cursor: pointer" @click="handleMenu(4, row)">{{
                    row.name
                    }}</span>
            </template>
            <!-- <template #link-form="{}">
        <div v-for="(item,index) in form.informationList" :key="index">
          <el-upload
            v-model:file-list="item.link"
            class="upload-demo"
            action="/api/blade-resource/oss/endpoint/put-file"
            multiple
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :limit="1"
            :on-exceed="handleExceed"
            :with-credentials="true"
            :headers="headers"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </div>
      </template> -->
        </avue-crud>
    </basic-container>
</template>
<script setup>
import { getList, getDetail, add, update, remove } from '@/api/casemanagement/caseManagement';
import option from '@/option/casemanagement/caseManagement';
import { useStore } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import website from '@/config/website';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { addFromCaseManagement } from '@/api/casemanagement/caseManagement';
const router = useRouter();
const route = useRoute();
const crud = ref(null);
const store = useStore();
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
    pageSize: 10,
    currentPage: 1,
    total: 0,
});
const selectionList = ref([]);
const options = ref(option);
const data = ref([]);

const routerQuery = ref({});
routerQuery.value = route.query;

const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
    addBtn: validData(permission.value.caseManagement_add, false),
    // viewBtn: validData(permission.value.caseManagement_view, false),
    viewBtn: validData(false),
    delBtn: validData(permission.value.caseManagement_delete, false),
    editBtn: validData(permission.value.caseManagement_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
    return selectionList.value.map(ele => ele.id).join(',');
});

// 操作栏按钮点击
/*
  type 0：查看
  type 1：编辑
  type 2：添加病例
  type 3：删除
  type 4：列表姓名点击
  type 5：选择点击
*/
const handleMenu = (type, row, index) => {
    if (type === 0 || type === 1 || type === 4) {
        if (routerQuery.value.selectTab) return;
        router.push({
            path: '/casemanagement/tabs',
            query: {
                selectTab: 1,
                caseManagementId: row.id || null,
            },
        });
    }

    if (type === 2) {
        if (routerQuery.value.selectTab) return;
        router.push({
            path: '/casemanagement/tabs',
            query: {
                selectTab: 2,
                caseManagementId: row.id || null,
            },
        });
    }

    if (type === 3) {
        crud.value.rowDel(row, index);
    }
    if (type === 5) {
        initGoBackCase(row);
    }
};

// 路由跳转到病历页面
const initGoBackCase = async (row) => {
    if (row) {
        let params = { trialId: routerQuery.value.trialId, groupId: routerQuery.value.groupId, caseId: row.id }
        await addFromCaseManagement(params)
    }
    router.replace({
        path: '/trial/menu',
        query: {
            ...routerQuery.value,
        },
    });
};

import { Base64 } from 'js-base64';
const headers = ref({
    Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
    'Blade-Requested-With': 'BladeHttpRequest',
});
// 上传图片之前钩子
const beforeUpload = () => {
    headers.value[website.tokenHeader] = 'bearer ' + getToken();
};
// 响应式变量：用于存储文件列表
const fileList = ref([]);
// 上传成功钩子
const handleSuccess = (response, file, fileList) => {
    console.log('上传成功', response, file, fileList, form.value);
    // form.value.link = response.data.link;
    // form.value.name = response.data.originalName;
};

// 方法：文件超出限制时的处理
const handleExceed = (files, fileList) => {
    ElMessage.warning(
        `上传文件数量超过限制，当前选择了 ${files.length} 个文件，最大允许上传 1 个文件`
    );
};
onMounted(() => {
    options.value.detail = false;
    options.value.addBtn = routerQuery.value.selectTab ? false : true;
});
const rowSave = (row, done, loading) => {
    if (row.jzd instanceof Array) {
        row.jzd = row.jzd.join(',');
    }
    row.type = routerQuery.value.type;
    add(row)
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
            done();
        })
        .catch(error => {
            loading();
            window.console.console.log(error);
        });
};

const rowUpdate = (row, index, done, loading) => {
    if (row.jzd instanceof Array) {
        row.jzd = row.jzd.join(',');
    }
    update(row)
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
            done();
        })
        .catch(error => {
            loading();
            window.console.console.log(error);
        });
};

const rowDel = row => {
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(row.id);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};

const handleDelete = () => {
    if (selectionList.value.length === 0) {
        ElMessage.warning('请选择至少一条数据');
        return;
    }
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(ids.value);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};

const handleExport = () => {
    const downloadUrl = `/blade-casemanagement/caseManagement/export-caseManagement?${website.tokenHeader
        }=${getToken()}`;
    const { name } = query.value;
    let values = {
        name_: name,
    };

    ElMessageBox.confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
            downloadXls(res.data, `我的病例${dateNow()}.xlsx`);
            NProgress.done();
        });
    });
};

const beforeOpen = (done, type) => {
    if (['edit', 'view'].includes(type)) {
        getDetail(form.value.id).then(res => {
            form.value = res.data.data;
        });
    }
    done();
};

const searchReset = () => {
    query.value = {};
    onLoad(page.value);
};

const searchChange = (params, done) => {
    
    
    query.value = params;
    page.value.currentPage = 1;
    onLoad(page.value, params);
    done();
};

const selectionChange = list => {
    selectionList.value = list;
};

const selectionClear = () => {
    selectionList.value = [];
    crud.value.toggleSelection();
};

const currentChange = currentPage => {
    page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
    page.value.pageSize = pageSize;
};

const refreshChange = () => {
    onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
    loading.value = true;
    console.log('params',params);
    
    let values = {
        descs: 'create_time',
        ...params,
        type: routerQuery.value.type ?  routerQuery.value.type :  params.type,
    };
    getList(page.currentPage, page.pageSize, values).then(res => {
        const DATA = res.data.data;
        page.total = DATA.total;
        data.value = DATA.records;
        data.value.forEach(ele => {
            ele.jzdText = ele.jzd;
        });

        loading.value = false;
        selectionClear();
    });
};
</script>
